from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from record.models import *
from record.ser import *
from tools.mySnowId import get_snowId
import uuid
from tools.myredis import mredis


# Create your views here.
# 查看、增加体重记录
class WeightRecordView(APIView):
    def get(self, request,pet_id):
        records = WeightModel.objects.filter(id=pet_id)
        ser = WeightSerializer(records,many=True)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        # 幂等性验证
        recordUuid = request.query_params.get('recordUuid')
        if not mredis.str_get(recordUuid):
            return Response({'code': 20001, 'msg': '重复请求，请刷新重试'})

        ser = WeightSerializer(data=request.data)
        if not ser.is_valid():
            return Response({'code': 200, 'msg': '参数不正确'})
        ser.save()
        mredis.str_del(recordUuid)
        return Response({'code': 200, 'msg': '添加成功','data':ser.data})


# 查看、增加饮食记录
class DiteRecordView(APIView):
    def get(self, request):
        diet = DietModel.objects.all()
        ser = DietSerializer(diet, many=True)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        ser = DietSerializer(data=request.data)
        if not ser.is_valid():
            return Response({'code': 200, 'msg': '参数不正确'})
        ser.save()
        return Response({'code': 200, 'msg': '添加成功','data':ser.data})


# 增加饮食记录，分表版
class DiteRecordShuntView(APIView):
    def post(self, request):
        data = request.data
        # 获取pet_id
        pet_id = data.get('pet_id')
        # 判断pet_id是否合法
        try:
            pet_id = int(pet_id)
            pet = PetModel.objects.get(id=pet_id)
        except:
            return Response({'code': 200, 'msg': 'pet_id不正确'})
        # 获取雪花算法Id
        data = dict(data)
        snow_id = get_snowId()
        # print('-' * 20, snow_id)
        data['id'] = snow_id
        # print(data)
        # pet_id hash分表
        hash_id = hash(pet_id) % 3
        try:
            if hash_id == 0:
                DietOneModel.objects.create(**data)
            elif hash_id == 1:
                DietTwoModel.objects.create(**data)
            else:
                DietThreeModel.objects.create(**data)
        except Exception as e:
            return Response({'msg': '参数不正确', 'error': e})

        return Response({'code': 200, 'msg': '添加成功'})


# 查看、增加尿便记录
class PeeRecordView(APIView):
    def get(self, request):
        pee = PeeModel.objects.all()
        ser = PeeSerializer(pee, many=True)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        ser = PeeSerializer(data=request.data)
        if not ser.is_valid():
            return Response({'code': 200, 'msg': '参数不正确'})
        ser.save()
        return Response({'code': 200, 'msg': '添加成功','data':ser.data})


# 查看、增加健康记录
class HealthRecordView(APIView):
    def get(self, request):
        pee = HealthModel.objects.all()
        ser = HealthSerializer(pee, many=True)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        ser = HealthSerializer(data=request.data)
        if not ser.is_valid():
            return Response({'code': 200, 'msg': '参数不正确'})
        ser.save()
        return Response({'code': 200, 'msg': '添加成功','data':ser.data})


# 查看、增加洗护记录
class ClearRecordView(APIView):
    def get(self, request):
        pee = ClearoutModel.objects.all()
        ser = ClearoutSerializer(pee, many=True)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data}, status=status.HTTP_200_OK)

    def post(self, request):
        ser = ClearoutSerializer(data=request.data)
        if not ser.is_valid():
            return Response({'code': 200, 'msg': '参数不正确'})
        ser.save()
        return Response({'code': 200, 'msg': '添加成功','data':ser.data})


# 分别获取体重表中的体重、饮食表中的喂食重量、尿便中的便尿类型、健康中的健康项目、洗护中的清洗项目
class RecordSView(APIView):
    def get(self, request, pet_id):
        # Define mappings for choices
        pee_choices = {'1': '小便', '2': '大便', '3': '尿'}
        health_choices = {'1': '驱虫', '2': '打疫苗'}
        clearout_choices = {'1': '洗澡', '2': '修指甲'}

        # Get the latest records for each model by pet_id
        weight = WeightModel.objects.filter(pet_id=pet_id).order_by('-recodetime').values('weight').first()
        foodweight = DietModel.objects.filter(pet_id=pet_id).order_by('-recodetime').values('foodweight').first()
        pee = PeeModel.objects.filter(pet_id=pet_id).order_by('-recodetime').values('pee').first()
        health = HealthModel.objects.filter(pet_id=pet_id).order_by('-recodetime').values('health').first()
        clearout = ClearoutModel.objects.filter(pet_id=pet_id).order_by('-recodetime').values('clearout').first()

        # Aggregate results with choice mappings applied
        data = {
            'weight': weight['weight'] if weight else None,
            'foodweight': foodweight['foodweight'] if foodweight else None,
            'pee': pee_choices.get(pee['pee']) if pee else None,
            'health': health_choices.get(health['health']) if health else None,
            'clear': clearout_choices.get(clearout['clearout']) if clearout else None,
        }

        return Response(data, status=status.HTTP_200_OK)


# 生成uuid
class UuidView(APIView):
    def get(self, request):
        uu = uuid.uuid4()
        # print(uu, type(uu))
        uuid4 = str(uu)
        # print(uuid4)
        # 幂等性操作，将uuid存入redis中
        mredis.str_set(uuid4, uuid4)
        return Response({'code': 200, 'msg': '生成成功', 'uuid4': uuid4})